package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.example.myapplication.bean.LoginBean;
import com.example.myapplication.net.Common;
import com.example.myapplication.utils.AESEncryptUtils;
import com.example.myapplication.utils.Constants;
import com.example.myapplication.utils.OkHttp3_0Utils;
import com.example.myapplication.utils.QZXTools;
import com.example.myapplication.utils.SharedPreferenceUtil;
import com.hjq.toast.ToastUtils;


import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.et_login_username)
    EditText et_login_username;

    @BindView(R.id.et_login_password)
    EditText et_login_password;


    @BindView(R.id.rl_base)
    RelativeLayout rl_base;

    @BindView(R.id.rl_login_button)
    RelativeLayout rl_login_button;

    public static final String TAG = "LoginActivity";
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        ButterKnife.bind(this);


        String token = SharedPreferenceUtil.getInstance(MyAPP.getInstance()).getString("token");
        if (TextUtils.isEmpty(token)){
            initData();
            addActivity(this);
            initListener();
        }else {
            Intent intent = new Intent(LoginActivity.this, LoadImageActivity.class);
         //   Intent intent = new Intent(LoginActivity.this, LoadImageTestActivity.class);
            startActivity(intent);
            finish();

        }




    }

    private void initListener() {
        rl_login_button.setOnClickListener(this);
    }

    private void initData() {
        String username = SharedPreferenceUtil.getInstance(MyAPP.getInstance()).getString("username");
        String password = SharedPreferenceUtil.getInstance(MyAPP.getInstance()).getString("password");
        if (!TextUtils.isEmpty(username)){
            et_login_username.setText(username);
            et_login_username.setSelection(username.length());
        }
        if (!TextUtils.isEmpty(password)){
            et_login_password.setText(password);
            et_login_password.setSelection(password.length());
        }

    }

    @Override
    protected void handleActMessage(Message msg) {
        super.handleActMessage(msg);
        switch (msg.what) {
            case Common.Interface_err:
                String info = (String) msg.obj;
                ToastUtils.show(info);
                dismissWaitingDlg();
                break;
            case Common.Interface_success:
                dismissWaitingDlg();
                LoginBean loginBean = (LoginBean) msg.obj;
                String version = loginBean.getVersion();
                LoginBean.DataDTO loginBeanData = loginBean.getData();
                String token = loginBeanData.getToken();
                int userId = loginBeanData.getId();
                Integer cityId = loginBeanData.getCityId();

                SharedPreferenceUtil.getInstance(MyAPP.getInstance()).setString("token", token);
                SharedPreferenceUtil.getInstance(MyAPP.getInstance()).setString("userId", userId+"");
                SharedPreferenceUtil.getInstance(MyAPP.getInstance()).setString("versionCode", version);
                SharedPreferenceUtil.getInstance(MyAPP.getInstance()).setString("cityId", cityId+"");

               Intent intent = new Intent(LoginActivity.this, LoadImageActivity.class);
              //  Intent intent = new Intent(LoginActivity.this, LoadImageTestActivity.class);
                startActivity(intent);
                finish();

                break;

        }
    }





    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_login_button:
                String userName = et_login_username.getText().toString().trim();
                String passWord = et_login_password.getText().toString().trim();
                if (TextUtils.isEmpty(userName)){
                    ToastUtils.show("用户名不能为空");
                    return;
                }
                if (TextUtils.isEmpty(passWord)){
                    ToastUtils.show("密码不能为空");
                    return;
                }

                login(userName, passWord);

                break;
        }
    }

    private void login(String userName, String passWord) {
        showWaitingDlg();
        String url = Common.LOGIN;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("username", userName);
            jsonObject.put("password", passWord);
            String encrypt = AESEncryptUtils.encrypt(jsonObject.toString(), Constants.DECRYPT_KEY);
            OkHttp3_0Utils.getInstance().asyncBodyEncryptStringOkHttp(url, encrypt, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    Message message = Message.obtain();
                    message.what = Common.Interface_err;
                    message.obj = "当前服务登录失败";
                    baseHandler.sendMessage(message);
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String content = response.body().string();
                    QZXTools.logE("onResponse: " + content, null);
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(content);
                        int code = jsonObject.optInt("code");
                        String msg = jsonObject.optString("message");
                        String version = jsonObject.optString("version");
                        String timestamp = jsonObject.optString("timestamp");

                        if (code == 200) {
                            String realData = jsonObject.optString("data");
                            String decryData = AESEncryptUtils.decrypt(realData, Constants.DECRYPT_KEY);
                            QZXTools.logD(TAG, decryData);

                            com.alibaba.fastjson.JSONObject jsonObjectReal = new com.alibaba.fastjson.JSONObject();

                            jsonObjectReal.put("version", version);
                            jsonObjectReal.put("code", code);
                            jsonObjectReal.put("message", msg);
                            jsonObjectReal.put("data", JSON.parseObject(decryData));
                            jsonObjectReal.put("timestamp", timestamp);
                            String realContent = jsonObjectReal.toString();
                            QZXTools.logD(TAG, realContent);



                            LoginBean loginBean = JSON.parseObject(realContent, LoginBean.class);
                            Message message = Message.obtain();
                            message.what = Common.Interface_success;
                            message.obj = loginBean;
                            baseHandler.sendMessage(message);

                            SharedPreferenceUtil.getInstance(MyAPP.getInstance()).setString("username", userName);
                            SharedPreferenceUtil.getInstance(MyAPP.getInstance()).setString("password", passWord);
                        } else {
                            Message message = Message.obtain();
                            message.what = Common.Interface_err;
                            message.obj = msg;
                            baseHandler.sendMessage(message);
                        }
                    } catch (Exception e) {
                        Message message = Message.obtain();
                        message.what = Common.Interface_err;
                        message.obj = "当前服务登录失败";
                        baseHandler.sendMessage(message);
                    }


                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeActivity(this);
    }
}
